<template>
  <div>
    <div class="i-layout-page-header">
      <PageHeader class="product_tabs" hidden-breadcrumb>
        <div slot="title">
          <router-link :to="{ path: '/admin/marketing/store_package/index' }"
            ><Button icon="ios-arrow-back" size="small" class="mr20"
              >返回</Button
            ></router-link
          >
          <span
            v-text="$route.params.id ? '编辑卡包' : '新建卡包'"
            class="mr20"
          ></span>
        </div>
      </PageHeader>
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form :model="formData" :label-width="150">
        <FormItem label="卡包名称：">
          <Input v-model="formData.title" placeholder="请输入卡包名称"></Input>
        </FormItem>
        <FormItem prop="image">
          <div class="custom-label" slot="label">
            <div>
              <div>卡包封面</div>
            </div>
            <div>：</div>
          </div>
          <div class="picBox" @click="modalPicTap('dan', 'danFrom')">
            <div class="pictrue" v-if="formData.image">
              <img v-lazy="formData.image" />
            </div>
            <div class="upLoad acea-row row-center-wrapper" v-else>
              <Icon type="ios-camera-outline" size="26" class="iconfonts" />
            </div>
          </div>
        </FormItem>
        <FormItem label="发放级别：">
          <CheckboxGroup v-model="selectedLevels">
            <Checkbox
              v-for="level in userLevelListApi"
              :key="level.grade"
              :label="level.grade"
            >
              {{ level.name }}
            </Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="卡包类型：">
          <RadioGroup v-model="formData.type">
            <Radio :label="1">闺蜜卡包</Radio>
            <Radio :label="2">权益卡包</Radio>
            <Radio :label="3">抽奖卡包</Radio>
            <Radio :label="4">商品卡包</Radio>
            <Radio :label="5">生日卡包</Radio>
            <Radio :label="6">年终回馈</Radio>
            <Radio :label="7">手动领取</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="消费级别：" v-if="formData.type == 6">
          <CheckboxGroup v-model="consumeLevels">
            <Checkbox
              v-for="level in consumeListApi"
              :key="level.grade"
              :label="level.grade"
            >
              {{ level.name }}
            </Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="闺蜜卡包描述：" prop="" v-if="formData.type == 1">
          <vue-ueditor-wrap
                v-model="formData.share_descr"
                :key="1"
                @beforeInit="addCustomDialog2"
                :config="myConfig"
                style="width: 90%"
          ></vue-ueditor-wrap>
        </FormItem>
        <FormItem label="卡包描述：" prop="">
          <vue-ueditor-wrap
                v-model="formData.rule_descr"
                :key="1"
                @beforeInit="addCustomDialog"
                :config="myConfig"
                style="width: 90%"
          ></vue-ueditor-wrap>
        </FormItem>
        <FormItem label="发放时间：">
          <DatePicker
            :value="datetime1"
            :editable="false"
            type="datetimerange"
            placeholder="在这个时间内登录发放"
            @on-change="dateChange1"
          ></DatePicker>
        </FormItem>
        <FormItem label="使用时间：">
          <DatePicker
            :value="datetime2"
            :editable="false"
            type="datetimerange"
            placeholder="领取后在这个时间段内可以使用"
            @on-change="dateChange2"
          ></DatePicker>
        </FormItem>
        <FormItem label="使用时间：">
            <InputNumber
                :min="0"
                :max="10000"
                v-model="formData.use_day"
                placeholder="特殊卡包使用时间天数"
            ></InputNumber>
        </FormItem>
        <FormItem label="发放形式：">
          <RadioGroup v-model="formData.issue_type">
            <Radio :label="1">直接到账</Radio>
            <Radio :label="2">仅分享</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="image" v-if="formData.issue_type == 2">
          <div class="custom-label" slot="label">
            <div>
              <div>分享图</div>
            </div>
            <div>：</div>
          </div>
          <div class="picBox" @click="modalPicTap2('dan', 'danFrom')">
            <div class="pictrue" v-if="formData.share_image">
              <img v-lazy="formData.share_image" />
            </div>
            <div class="upLoad acea-row row-center-wrapper" v-else>
              <Icon type="ios-camera-outline" size="26" class="iconfonts" />
            </div>
          </div>
        </FormItem>
        <FormItem label="邀请奖励：">
          <RadioGroup v-model="formData.is_award">
            <Radio :label="-1">无</Radio>
            <Radio :label="1">有</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="奖励类型："
          v-if="formData.is_award == 1 && formData.is_award == 1"
        >
          <RadioGroup v-model="formData.award_type">
            <Radio :label="1">积分</Radio>
            <Radio :label="2">权益卡包</Radio>
            <Radio :label="3">优惠券</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="赠送优惠券：" v-if="formData.award_type == 3 && formData.is_award == 1">
            <div v-if="couponName.length" class="mb20">
              <Tag
                closable
                v-for="(item, index) in couponName"
                :key="index"
                @on-close="handleClose(item)"
                >{{ item.title }}</Tag
              >
            </div>
            <Button type="primary" @click="addCoupon">添加优惠券</Button>
        </FormItem>
        <FormItem
          label="先择发放卡包:"
          v-if="formData.award_type == 2 && formData.is_award == 1"
        >
          <Select v-model="formData.card_pack_id" style="width: 320px">
            <Option
              v-for="item in kaList"
              :value="item.pid"
              :key="item.pid"
              >{{ item.title }}</Option
            >
          </Select>
          <div class="info">选择闺密卡包</div>
        </FormItem>
        <FormItem
          label="奖励积分数量:"
          v-if="formData.award_type == 1 && formData.is_award == 1"
        >
          <InputNumber
            :min="1"
            v-model="formData.store_num"
            :precision="0"
          ></InputNumber>
        </FormItem>
        <FormItem label="状态：">
          <RadioGroup v-model="formData.is_show">
            <Radio :label="1">开启</Radio>
            <Radio :label="0">关闭</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="save" :disabled="disabled"
            >立即创建</Button
          >
        </FormItem>
      </Form>
    </Card>
    <Modal
      v-model="modals"
      title="商品列表"
      footerHide
      class="paymentFooter"
      scrollable
      width="900"
      @on-cancel="cancel"
    >
      <goods-list
        ref="goodslist"
        v-if="modals"
        :ischeckbox="true"
        @getProductId="getProductId"
      ></goods-list>
    </Modal>
    <!-- 上传图片-->
    <Modal
      v-model="modalPic"
      width="950px"
      scrollable
      footer-hide
      closable
      title="上传商品图"
      :mask-closable="false"
      :z-index="1"
    >
      <uploadPictures
        :isChoice="isChoice"
        @getPic="getPic"
        v-if="modalPic"
      ></uploadPictures>
    </Modal>
    <Modal
      v-model="modalPic2"
      width="950px"
      scrollable
      footer-hide
      closable
      title="上传商品图"
      :mask-closable="false"
      :z-index="1"
    >
      <uploadPictures
        :isChoice="isChoice"
        @getPic="getPic2"
        v-if="modalPic2"
      ></uploadPictures>
    </Modal>
    <coupon-list
      ref="couponTemplates"
      @nameId="nameId"
      :couponids="formData.coupons"
      :updateIds="updateIds"
      :updateName="updateName"
    ></coupon-list>
  </div>
</template>

<script>
import { mapState } from "vuex";
import goodsList from "@/components/goodsList/index";
import {
  couponCategoryApi,
  couponSaveApi,
  couponDetailApi,
  cardpackApi,
  cardpackDetailApi,
  cardListApi,
} from "@/api/marketing";
import { viplistTwotApi,vipListConsume } from "@/api/user";
import uploadPictures from "@/components/uploadPictures";
import VueUeditorWrap from "vue-ueditor-wrap";
import couponList from "@/components/couponList";
// import { formatDate } from '@/utils/validate';
export default {
  name: "storePackageCreate",
  components: {
    goodsList,
    uploadPictures,
    VueUeditorWrap,
    couponList
  },
  data() {
    return {
      disabled: false,
      formData: {
        title: "", //标题
        image: "", //封面图片
        type: 1, //卡包分类
        rule_descr: "", //规则描述
        share_descr: "", //规则描述
        issue_type: 1, //发放形式
        is_award: -1, //邀请奖励
        award_type: 1, //奖励类型
        store_num: 0, //积分数量
        begin_time: 0, //开始时间
        end_time: 0, //结束时间
        sort: 0, //排序
        is_show: 1, //开启关闭状态
        card_pack_id: 0, //选择的卡包id
        level: "", //卡包级别id
        send_begin_time: "", //开始发放
        send_end_time: "", //结束发放
        share_image:"",//分享图
        use_day: 0, //可使用天数
        coupons: [],
      },
      couponName: [],
      categoryList: [],
      isReceiveTime: 0,
      modals: false,
      datetime1: [],
      datetime2: [],
      // 上传图片
      modalPic: false,
      modalPic2: false,
      isChoice: "",
      picTit: "",
      tableIndex: 0,
      selectedLevels: [], // 用于存储用户选择的卡包级别的 ID
      userLevelListApi: [], // 用于存储从接口获取的卡包级别数据
      consumeLevels: [], //消费级别
      consumeListApi:[],
      kaList: [], //用于存储卡包信息
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器宽度
        UEDITOR_HOME_URL: "/admin/UEditor/",
        serverUrl: "",
      },
      updateIds: [],
      updateName: [],
      distinguish:"copy",  //判断新增还是编辑
    };
  },
  computed: {
    ...mapState("admin/layout", ["isMobile"]),
  },
  mounted() {
    if(this.$route.query.type){
      this.distinguish = this.$route.query.type; // 'edit' 或 'copy'
    }
  },
  created() {
    //用户等级列表
    this.levelListApi();
    // 用户消费级别
    this.getListConsume();
    // 卡包列表
    this.getList();
    this.getCategoryList();
    if (this.$route.params.id) {
      this.getCouponDetail();
    }
  },
  watch: {
    selectedLevels: {
      handler(newValue) {
        // 将选中的卡包级别的 ID 以逗号分隔的形式存储在 formData.level 中
        this.formData.level = newValue.join(",");
        // console.log("选中的值：", this.formData.level);
      },
      immediate: true, // 立即执行以初始化 formData.level
    },
    consumeLevels: {
      handler(newValue) {
        // 将选中的卡包级别的 ID 以逗号分隔的形式存储在 formData.grade 中
        this.formData.level = newValue.join(",");
        // console.log("选中的值：", this.formData.grade);
      },
      immediate: true, // 立即执行以初始化 formData.grade
    },
  },
  methods: {
     // 添加优惠券
     addCoupon() {
      this.$refs.couponTemplates.isTemplate = true;
      this.$refs.couponTemplates.tableList();
    },
    nameId(id, names) {
      this.formData.coupons = id;
      this.couponName = this.unique(names);
    },
    handleClose(name) {
      let index = this.couponName.indexOf(name);
      this.couponName.splice(index, 1);
      let couponIds = this.formData.coupons;
      couponIds.splice(index, 1);
      this.updateIds = couponIds;
      this.updateName = this.couponName;
    },
     //对象数组去重；
     unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
    },
    // 添加自定义弹窗
    addCustomDialog(editorId) {
      window.UE.registerUI(
        "test-dialog",
        function(editor, uiName) {
          // 创建 dialog
          let dialog = new window.UE.ui.Dialog({
            // 指定弹出层中页面的路径，这里只能支持页面，路径参考常见问题 2
            iframeUrl: "/admin/widget.images/index.html?fodder=dialog",
            // 需要指定当前的编辑器实例
            editor: editor,
            // 指定 dialog 的名字
            name: uiName,
            // dialog 的标题
            title: "上传图片",
            // 指定 dialog 的外围样式
            cssRules: "width:1200px;height:500px;padding:20px;",
          });
          this.dialog = dialog;
          var btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render();
              dialog.open();
            },
          });
          return btn;
        },
      );
    },
    addCustomDialog2(editorId) {
      window.UE.registerUI(
        "test-dialog",
        function(editor, uiName) {
          // 创建 dialog
          let dialog = new window.UE.ui.Dialog({
            // 指定弹出层中页面的路径，这里只能支持页面，路径参考常见问题 2
            iframeUrl: "/admin/widget.images/index.html?fodder=dialog",
            // 需要指定当前的编辑器实例
            editor: editor,
            // 指定 dialog 的名字
            name: uiName,
            // dialog 的标题
            title: "上传图片",
            // 指定 dialog 的外围样式
            cssRules: "width:1200px;height:500px;padding:20px;",
          });
          this.dialog = dialog;
          var btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render();
              dialog.open();
            },
          });
          return btn;
        },
      );
    },
    getList() {
      let tableFrom = {
        is_show: 1,
        issue_type: 1,
      };
      cardListApi(tableFrom)
        .then(async (res) => {
          this.kaList = res.data.list;
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    levelListApi() {
      viplistTwotApi().then((res) => {
        this.userLevelListApi = res.data.list.filter(
          (level) => level.is_show === 1
        );
      });
    },
    getListConsume() {
      vipListConsume().then((res) => {
        this.consumeListApi = res.data.list
      });
    },
    // 点击商品图
    modalPicTap(tit, picTit, index) {
      this.modalPic = true;
      this.isChoice = tit === "dan" ? "单选" : "多选";
      this.picTit = picTit;
      this.tableIndex = index;
    },
    // 点击商品图
    modalPicTap2(tit, picTit, index) {
      this.modalPic2 = true;
      this.isChoice = tit === "dan" ? "单选" : "多选";
      this.picTit = picTit;
      this.tableIndex = index;
    },
    // 获取单张图片信息
    getPic(pc) {
      switch (this.picTit) {
        case "danFrom":
          this.formData.image = pc.att_dir;
          break;
        // case 'danTable':
        //     this.specsData[this.tableIndex].pic = pc.att_dir;
        //     break;
        default:
          if (!!this.formData.attrs && this.formData.attrs.length) {
            this.$set(this.specsData[this.tableIndex], "_checked", true);
          }
          this.specsData[this.tableIndex].pic = pc.att_dir;
      }
      this.modalPic = false;
    },
    getPic2(pc) {
      switch (this.picTit) {
        case "danFrom":
          this.formData.share_image = pc.att_dir;
          break;
        // case 'danTable':
        //     this.specsData[this.tableIndex].pic = pc.att_dir;
        //     break;
        default:
          if (!!this.formData.attrs && this.formData.attrs.length) {
            this.$set(this.specsData[this.tableIndex], "_checked", true);
          }
          this.specsData[this.tableIndex].pic = pc.att_dir;
      }
      this.modalPic2 = false;
    },
    // 品类
    getCategoryList() {
      couponCategoryApi(1).then(async (res) => {
        res.data.forEach((val) => {
          val.cate_name = `${val.html}${val.cate_name}`;
        });
        this.categoryList = res.data;
      });
    },
    // 卡包
    getCouponDetail() {
      cardpackDetailApi(this.$route.params.id)
        .then((res) => {
          let data = res.data.info;
          this.formData.title = data.title;
          this.formData.image = data.image;
          this.formData.type = data.type;
          this.formData.rule_descr = data.rule_descr;
          this.formData.share_descr = data.share_descr;
          this.formData.issue_type = data.issue_type;
          this.formData.use_day = data.use_day;
          this.formData.award_type = data.award_type;
          this.formData.is_award = data.is_award;
          this.formData.store_num = data.store_num;
          this.formData.begin_time = data.begin_time;
          this.formData.end_time = data.end_time;
          this.formData.send_begin_time = data.send_begin_time;
          this.formData.send_end_time = data.send_end_time;
          this.formData.sort = data.sort;
          this.formData.is_show = data.is_show;
          this.formData.card_pack_id = data.card_pack_id;
          this.formData.share_image = data.share_image;
          if(data.level && data.level!=="" && data.type == 6){
            this.formData.level = data.level;
            if (data.level.length > 0) {
              this.consumeLevels = data.level.split(",").map(Number);
            } else {
              this.consumeLevels = [];
            }
          }else{
            this.formData.level = data.level;
            if (data.level.length > 0) {
              this.selectedLevels = data.level.split(",").map(Number);
            } else {
              this.selectedLevels = [];
            }
          }
          // console.log(this.formData.level,"4563")
          // console.log(this.selectedLevels,"4563")
          this.datetime1 = [data.send_begin_time+'00:00:00', data.send_end_time+'00:00:00'];
          this.datetime2 = [data.begin_time+'00:00:00', data.end_time+'00:00:00'];
          this.couponName = data.coupons;
          if(data.coupons){
            let ids = data.coupons.map(item => item.id).sort((a, b) => b - a);
            this.formData.coupons = ids
          }

        })
        .catch((err) => {
          this.$Message.error(err.msg);
        });
    },
    makeDate(data) {
      let date = new Date(data);
      let YY = date.getFullYear() + "-";
      let MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    // 创建
    save() {
      if (this.formData.type == 1 && this.formData.issue_type!=2) {
        return this.$Message.error("请选择发放方式为仅分享");
      }
      if (!this.formData.title) {
        return this.$Message.error("请输入卡包名称");
      }
      if (!this.formData.image) {
        return this.$Message.error("请选择封面图片");
      }
      // if (!this.formData.level) {
      //   return this.$Message.error("请选择卡包级别");
      // }
      if (!this.formData.rule_descr) {
        return this.$Message.error("请填写卡包描述");
      }
      // if (this.formData.begin_time === 0 || this.formData.end_time === 0) {
      //   return this.$Message.error("请选择领取时间");
      // }
      // if (this.formData.issue_type == 1) {
      //   this.formData.is_award = -1;
      //   this.formData.store_num = 0;
      // }
      // if (this.formData.issue_type == 2 && this.formData.award_type == 1) {
      //   if (!this.formData.store_num) {
      //     return this.$Message.error("请填积分发放数量");
      //   }
      // }
      if (this.formData.issue_type == 2 && this.formData.award_type == 2) {
        if (this.formData.card_pack_id === 0) {
          return this.$Message.error("请选择需要发放的卡包");
        }
      }
      this.disabled = false;
      let id = 0;
      if(this.distinguish == 'edit'){
        id = this.$route.params.id;
      }else{
        id = 0
      }
      
      cardpackApi(this.formData, id)
        .then((res) => {
          this.disabled = true;
          this.$Message.success(res.msg);
          setTimeout(() => {
            this.$router.push({
              path: "/admin/marketing/store_package/index",
            });
          }, 1000);
        })
        .catch((err) => {
          this.$Message.error(err.msg);
        });
    },
    // 限时
    dateChange1(time) {
      console.log(time);
      this.formData.send_begin_time = time[0];
      this.formData.send_end_time = time[1];
    },
    dateChange2(time) {
      console.log(time);
      this.formData.begin_time = time[0];
      this.formData.end_time = time[1];
    },
    cancel() {
      this.modals = false;
    },
  },
};
</script>

<style scoped>
.info {
  color: #888;
  font-size: 12px;
}
.ivu-form >>> .ivu-form-item-label {
  font-weight: 700;
  font-size: 14px !important;
}

.ivu-input-wrapper {
  width: 320px;
}

.ivu-radio-wrapper {
  margin-right: 30px;
  font-size: 14px !important;
}

.ivu-radio-wrapper >>> .ivu-radio {
  margin-right: 10px;
}

.ivu-input-number {
  width: 160px;
}

.ivu-date-picker {
  width: 320px;
}

.ivu-icon-ios-camera-outline {
  width: 120px;
  height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.02);
  line-height: 58px;
  cursor: pointer;
  vertical-align: middle;
}

.upload-list {
  width: 120px;
  height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;
  vertical-align: middle;
}

.upload-list img {
  display: block;
  width: 100%;
  height: 100%;
}

.ivu-icon-ios-close-circle {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
}
.custom-label {
  display: inline-flex;
  line-height: 1.5;
}
.picBox {
  display: inline-block;
  cursor: pointer;
}

.pictrue {
  width: 120px;
  height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  .btndel {
    position: absolute;
    z-index: 9;
    width: 20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
}
</style>
